
from wtforms import StringField, IntegerField, PasswordField
from wtforms.validators import DataRequired, Length, Email, Regexp, ValidationError

from apps.libs.enums import ClientTypeEnum
from apps.models.user import User
from apps.validators.base import BaseForm as Form


class ClientForm(Form):
    account = StringField(validators=[DataRequired(message='账号不允许为空'), Length(5, 20, message='账号长度不符合要求')])
    secret = PasswordField()
    type = IntegerField(validators=[DataRequired()])

    def validate_type(self, value):
        try:
            client = ClientTypeEnum(value.data)
        except ValueError as e:
            raise ValidationError(message='用户类型不符合要求')
        self.type.data = client


class UserEmailForm(ClientForm):
    account = StringField(validators=[DataRequired(message='账号不能为空'), Email(message='请填写正确的邮箱')])
    secret = StringField(validators=[DataRequired(message='密码不能为空'), Regexp(r'[a-zA-Z0-9]{6,22}')])
    nickname = StringField(validators=[DataRequired(message='用户名不能为空'), Length(2, 22, message='名称长度超限')])

    def validate_account(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError(message='此账号已存在！')

    def validate_nickname(self, field):
        if User.query.filter_by(nickname=field.data).first():
            raise ValidationError(message='用户名已被占用！')


class BookSearchForm(Form):
    q = StringField(validators=[DataRequired(message='搜索关键字不能为空')])